<?php


// C('WX_APP_ID')."&secret=".C('WX_APP_SECRET').

function getOpenID(){
	$openid = "";
	
	$code = $_GET['code'];
	
	if(!empty($code)){
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?".
				"appid=".C('WX_APP_ID')."&secret=".C('WX_APP_SECRET').
				"&code=".$_GET['code']."&grant_type=authorization_code";
		$re = file_get_contents($url);
		$uinfo = json_decode($re,true);
		$openid = $uinfo['openid'];
		cookie('openid',$openid,86400*100);
	}
	
	if(empty($openid)){
		$openid = cookie('openid');
		if(empty($openid)){
			$APPID = C('WX_APP_ID');
			
			/*
			 * 
			 */
// 			$URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$APPID}&redirect_uri="
// 					.urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']).
// 						"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
// 			header('location:'.$URL);
			//---------------------------------------------------------------
			$APPID = C('WX_APP_ID');
			$URL = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$url =  C('WX_OAUTH_DOMAIN')."?appid={$APPID}&scope=snsapi_base&state=hello-world&redirect_uri=".urlencode($URL);
			header('location:'.$url);
		}
	}
	
	return $openid;
	
}